﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using T2V.SharePoint.Report.DocXGenerator;
using Pesico.Forms.DocxGenerator;
using T2V.SharePoint.Common.Extensions;
using T2V.SharePoint.Common.Utilities;
using Pesico.Forms.Entities;
using Pesico.Forms.Services;
using Microsoft.SharePoint.Workflow;

namespace Pesico.Forms.EventReceiver
{
    public class ContractEventReceiver : SPItemEventReceiver
    {

        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            //
            UpdatApprovers(properties);
        }

        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            //
            ExportToDocx(properties.ListItem, Common.Constants.DOCX_TEMPLATE_LIST_URL);
        }

        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);
            //
            UpdatApprovers(properties);
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            //
            bool isWorkflowUpdate = false;
            foreach (SPWorkflow wf in properties.ListItem.Workflows)
            {
                if (wf.InternalState.Equals(SPWorkflowState.Locked | SPWorkflowState.Running) || wf.InternalState.Equals(SPWorkflowState.Running))
                {
                    isWorkflowUpdate = true;
                    break;
                }
            }
            if (!isWorkflowUpdate)
                ExportToDocx(properties.ListItem, Common.Constants.DOCX_TEMPLATE_LIST_URL);
        }

        #region Private Functions

        private void UpdatApprovers(SPItemEventProperties properties)
        {
            try
            {
                var approverWorkflowMappingItem = ApproverWorkflowMapping.GetItemByCreator(properties.CurrentUserId.ToString(), properties.Web);
                if (approverWorkflowMappingItem != null)
                {
                    if (!string.IsNullOrEmpty(approverWorkflowMappingItem.FinanceManager))
                        properties.AfterProperties["FinanceManager"] = approverWorkflowMappingItem.FinanceManager;
                    if (!string.IsNullOrEmpty(approverWorkflowMappingItem.LegalPerson))
                        properties.AfterProperties["LegalPerson"] = approverWorkflowMappingItem.LegalPerson;
                    if (!string.IsNullOrEmpty(approverWorkflowMappingItem.Signer))
                        properties.AfterProperties["Signer"] = approverWorkflowMappingItem.Signer;
                    if (!string.IsNullOrEmpty(approverWorkflowMappingItem.Printer))
                        properties.AfterProperties["Printer"] = approverWorkflowMappingItem.Printer;
                    if (!string.IsNullOrEmpty(approverWorkflowMappingItem.Admin))
                        properties.AfterProperties["Admin"] = approverWorkflowMappingItem.Admin;
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, "Pesico.Forms.EventReceiver.ContractEventReceiver UpdatApprovers");
            }
        }

        private void ExportToDocx(SPListItem item, string formTemplatesLib)
        {
            try
            {
                DocumentGenerator generator = GeneratorFactory.GetGenerator(item, formTemplatesLib);
                if (generator != null)
                {
                    var documentBytes = generator.GenerateDocument();

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(item.ParentList.ParentWeb.Site.ID))
                        {
                            using (SPWeb web = site.OpenWeb(item.ParentList.ParentWeb.ID))
                            {
                                using (DisableItemEvent disableItemEvent = new DisableItemEvent())
                                {
                                    var list = web.Lists[item.ParentList.ID];
                                    SPListItem spListItem = list.GetItemById(item.ID);
                                    if (spListItem.Attachments.Count > 0)
                                    {
                                        List<string> fileNames = new List<string>();

                                        foreach (string fileName in spListItem.Attachments)
                                        {
                                            fileNames.Add(fileName);
                                        }

                                        foreach (string fileName in fileNames)
                                        {
                                            spListItem.Attachments.DeleteNow(fileName);
                                        }
                                    }
                                    spListItem.Attachments.AddNow(string.Format("{0}_{1}_Original.docx", item.Title.ConvertToValidSharePointFileName(), DateTime.Now.ToString("yyyyMMdd")), documentBytes);
                                    spListItem.SystemUpdate();
                                }
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, "Pesico.Forms.EventReceiver.ContractEventReceiver ExportToDocx");
            }
        }

        #endregion Private Functions
    }
}
